* Finish creating analysis dataset - calls various do-files (all prexifed 5x)

* First create connected sets and produce cardiologist experience
do "$dofile/5a. create_set.do"
do "$dofile/5b. create_cardiologist_experience.do"

** Merge in the sets
use "$savedata/ami_analysis_mainspef.dta", clear

* Merge in the various connected sets
foreach x in 10 25 50 100{
cap drop _merge
merge m:1 trust_code using "$savedata/connect_total`x'.dta", keepusing(akm_set)
drop _merge
}

foreach x in 10 25 50 100{
	replace akm_set_mainspef`x'=0 if akm_set_mainspef`x'==.
}

gen one = 1

* Create hospital-doctor indicators (interact hosp and doctor id)
egen hdid = group(doctor_id trust_num) /* hospital doctor ID */
egen hyid = group(trust_num finyear) /* Hospital year ID */
egen doctime = group(doctor_id finyear) /* Doctor year ID */

* Create survival variables
foreach x in 7 30 90 365{
gen survive`x' = 1
replace survive`x' = 0 if all_death`x'==1 
}

forval x=1(1)20{
encode fulldiag3_`x', gen(di`x')
replace di`x'=0 if di`x'==.
}

* Make sure I have timing variables
cap drop admidate_month 
cap drop admidate_day 
cap drop admidate_year
cap drop dow

gen admidate_month = month(ami_date)
gen admidate_day = day(ami_date)
gen admidate_year = year(ami_date)

* Create day of the week
gen dow = dow(mdy(admidate_month, admidate_day, admidate_year))

* Generate A&e arrival variable
gen d_amb = aearrivalmode
replace d_amb = 9 if d_amb==.

/* Need to create this file */

merge m:1 pconsult finyear using "$savedata/cardio_experience0317.dta"
drop if _merge==2
*drop _merge10

* Create cardiologist experience variables
gen nonami3 = total3 - ami3
egen std_ami3 = std(ami3)
egen std_nonami3 = std(nonami3)

drop _merge

* Create secondary diagnosis variables
gen shock = 0
gen arrest = 0
gen arythmia = 0
gen arthero = 0

forval x=1(1)20{
	replace shock = 1 if substr(fulldiag3_`x',1,3)=="R57"
	replace arrest = 1 if substr(fulldiag3_`x',1,3)=="I46"
	replace arythmia = 1 if substr(fulldiag3_`x',1,3)=="I49"
	replace arthero = 1 if substr(fulldiag3_`x',1,4)=="I251"
}

cap drop stemi
gen stemi2 = 0

foreach x in I210 I211 I212 I213 I220 I221{
replace stemi2=1 if fulldiag3_1=="`x'"
}


egen vol_trust = sum(one), by(pconsult trust_num)

* Doctor FEs

foreach x in 10 25 50 100{
egen vol`x' = sum(one) if akm_set_mainspef`x'==1, by(pconsult)	
gen sample`x'=0
replace sample`x'=1 if akm_set_mainspef`x'==1 & vol_trust>=`x'
}

save "$savedata/masterdata.dta", replace
